import re
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
	message = db.StringProperty()

class XMPPHandler(webapp.RequestHandler):
    def getPostFix(self,strint):
        ops ={"*":2,"/":2,"+":1,"-":1}
        strint = strint.replace(' ','').replace('+',' + ').replace('-',' - ').replace('*',' * ').replace('/',' / ').replace('x',' * ').replace('(',' ( ').replace(')',' ) ')
        strint = '( '+strint+' )'
        lst = strint.split()
        fin = ""
        brStk = []
        for ch in lst:
            if ch == "(":
                tempStk = []   
                brStk.append(tempStk)
            elif ch == ')':
                lastStk = brStk.pop(-1)
                lastStk.reverse()
                fin += " ".join([str(x) for x in lastStk])+" "
            elif ch == "/" or ch == "*" or ch == "+" or ch == "-" :
                currentStk = brStk[-1]
                if len(currentStk) > 0:
                	while len(currentStk) > 0 and (ops[ch] == ops[currentStk[-1]] or ops[ch] < ops[currentStk[-1]]) :
                		fin += currentStk.pop(-1) + ' '
                currentStk.append(ch)
            else:
                fin += ch+" "
        return fin
	
    def saveLog(self,mesg):
        log = Log(message=mesg)	
        log.put()
        return "success I guess"

    def getValue(self,fin):
        stk = []
        fin2 = fin.split()
        for cur in fin2:
            if cur != "/" and cur != "*" and cur != "+" and cur != "-" :
                stk.append(float(cur))
            else:
                b = stk.pop(-1)
                a = stk.pop(-1)
                val = 0.0
                if cur == '+' :
                    val = a+b
                elif cur == '-' :
                    val = a-b
                elif cur == '*' :
                    val = a*b;
                elif cur == "/" :
                    val = a/b
                stk.append(val)
        return stk[0]
        
    def formatFinVal(self,finVal):
        decToInt = re.compile(r'\.0+$')
        ans = str(finVal)
        ans = decToInt.sub('',ans)    #remove trailing zeroes
        return ans
        
    def calc(self,strint):
        finStr = self.getPostFix(strint)
        finVal = self.getValue(finStr)
        ans = self.formatFinVal(finVal)
        return ans

    def post(self):
        message = xmpp.Message(self.request.POST)
        if message.body[0:4] == 'calc':
            message.reply('calculating....plzz wait')
            msg = message.body[4:]
            rslt = self.calc(msg)
            message.reply(rslt)
		#elif message.body[0:3] == 'log':
		#	rslt = saveLog(message.body[3:])
		#	message.reply(rslt)
        elif message.body[0:3] == 'log':
            msg = message.body[3:]
            rslt = self.saveLog(msg)
            message.reply(rslt)
        else:
            message.reply('sorry, invalid command !!')


application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

